package com.atguigu.gulimall.member.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.vo.MemberRegistVO;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.atguigu.gulimall.member.vo.UserLoginVO;
import org.omg.SendingContext.RunTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R regist(MemberRegistVO vo) {
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        //检查用户名和手机号是否唯一
        R cp = checkPhoneUnique(vo.getPhone());
        if (cp != null) return cp;
        R cu = checkUserNameUnique(vo.getUserName());
        if (cu != null) return cu;
        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        baseMapper.insert(memberEntity);
        return R.ok("注册成功");
    }

    @Override
    public R checkPhoneUnique(String phone) {
        MemberDao baseMapper = this.baseMapper;
        Integer check = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (check > 0) {
            return R.error("手机号码已被注册");
//            throw new RuntimeException("手机号码已被注册");
        }
        return null;
    }

    @Override
    public R checkUserNameUnique(String userNmae) {
        MemberDao baseMapper = this.baseMapper;
        Integer check = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userNmae));
        if (check > 0) {
            return R.error("用户名已存在");
//            throw new RuntimeException("用户名已存在");
        }
        return null;
    }

    @Override
    public MemberEntity login(UserLoginVO vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity != null) {
            //获取到数据库的password
            String passwordDB = memberEntity.getPassword();
            //密码匹配检查
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                return memberEntity;
            }
        }
        //登录失败
        return null;
    }

    @Override
    public MemberEntity otherLogin(SocialUser socialUser) {
        //合并登录和注册逻辑
        String uid = socialUser.getUid();
        //判断当前社交用户是否已经登录过系统
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //用户已存在
            memberEntity.setId(memberEntity.getId());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity);
            return memberEntity;
        }
        //用户不存在，进行注册
        MemberEntity regist = new MemberEntity();
        //获取社交账号用户信息
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("access_token", socialUser.getAccess_token());
            param.put("uid", socialUser.getUid());
            String resultString = HttpUtil.get("https://api.weibo.com/2/users/show.json", param);
            //{"id":5258336538,"idstr":"5258336538","class":1,"screen_name":"哲336","name":"哲336","province":"100","city":"1000","location":"其他","description":"","url":"","profile_image_url":"https://tva1.sinaimg.cn/crop.0.0.100.100.50/005JRrxEjw8el4ksc3uu6j302s02sglg.jpg?KID=imgbed,tva&Expires=1599205025&ssig=ererChbWnV","cover_image_phone":"http://ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg","profile_url":"u/5258336538","domain":"","weihao":"","gender":"m","followers_count":2,"friends_count":6,"pagefriends_count":0,"statuses_count":2,"video_status_count":0,"video_play_count":0,"favourites_count":0,"created_at":"Thu Oct 09 07:56:48 +0800 2014","following":false,"allow_all_act_msg":false,"geo_enabled":true,"verified":false,"verified_type":-1,"remark":"","email":"","insecurity":{"sexual_content":false},"status":{"visible":{"type":0,"list_id":0},"created_at":"Sun Nov 29 18:18:30 +0800 2015","id":3914581032084148,"idstr":"3914581032084148","mid":"3914581032084148","can_edit":false,"show_additional_indication":0,"text":"小米&微博感恩季，玩游戏狂送100台红米Note3！手机点击话题#红米Note3#或http://t.cn/RU13pP8 就能玩，还有机会赢小米手环、微博会员等海量好礼！千元旗舰，如你所愿：899元红米Note3，我最喜欢它的内置4000mAh大电池，续航持久，机身依然轻薄，我为它点赞！了解新品→http://t.cn/RU1lR6s ","source_allowclick":0,"source_type":1,"source":"<a href=\"http://app.weibo.com/t/feed/4cq1iX\" rel=\"nofollow\">微博活动</a>","favorited":false,"truncated":false,"in_reply_to_status_id":"","in_reply_to_user_id":"","in_reply_to_screen_name":"","pic_urls":[{"thumbnail_pic":"http://ww2.sinaimg.cn/thumbnail/a831c44fjw1eycgxt5jytj20u045zb29.jpg"}],"thumbnail_pic":"http://ww2.sinaimg.cn/thumbnail/a831c44fjw1eycgxt5jytj20u045zb29.jpg","bmiddle_pic":"http://ww2.sinaimg.cn/bmiddle/a831c44fjw1eycgxt5jytj20u045zb29.jpg","original_pic":"http://ww2.sinaimg.cn/large/a831c44fjw1eycgxt5jytj20u045zb29.jpg","geo":null,"is_paid":false,"mblog_vip_type":0,"reposts_count":0,"comments_count":0,"attitudes_count":0,"pending_approval_count":0,"isLongText":false,"reward_exhibition_type":0,"hide_flag":0,"mlevel":0,"biz_feature":0,"page_type":32,"hasActionTypeCard":0,"darwin_tags":[],"hot_weibo_tags":[],"text_tag_tips":[],"mblogtype":0,"rid":"0","userType":0,"more_info_type":0,"positive_recom_flag":0,"content_auth":0,"gif_ids":"","is_show_bulletin":0,"comment_manage_info":{"comment_permission_type":-1,"approval_comment_type":0},"pic_num":1},"ptype":0,"allow_all_comment":true,"avatar_large":"https://tva1.sinaimg.cn/crop.0.0.100.100.180/005JRrxEjw8el4ksc3uu6j302s02sglg.jpg?KID=imgbed,tva&Expires=1599205025&ssig=%2BfzZd7KbQV","avatar_hd":"https://tva1.sinaimg.cn/crop.0.0.100.100.1024/005JRrxEjw8el4ksc3uu6j302s02sglg.jpg?KID=imgbed,tva&Expires=1599205025&ssig=5pQzNBwSwL","verified_reason":"","verified_trade":"","verified_reason_url":"","verified_source":"","verified_source_url":"","follow_me":false,"like":false,"like_me":false,"online_status":0,"bi_followers_count":1,"lang":"zh-cn","star":0,"mbtype":0,"mbrank":0,"block_word":0,"block_app":0,"credit_score":80,"user_ability":0,"urank":2,"story_read_state":-1,"vclub_member":0,"is_teenager":0,"is_guardian":0,"is_teenager_list":0,"pc_new":0,"special_follow":false,"planet_video":0,"video_mark":0,"live_status":0}
            if (resultString != null) {
                JSONObject result = JSON.parseObject(resultString);
                String name = result.getString("name");
                String gender = result.getString("gender");
                regist.setUsername(name);
                regist.setNickname(name);
                regist.setGender("m".equals(gender)?1:0);
            }
        } catch (Exception e) {

        }
        regist.setSocialUid(socialUser.getUid());
        regist.setAccessToken(socialUser.getAccess_token());
        regist.setExpiresIn(socialUser.getExpires_in());
        baseMapper.insert(regist);
        return regist;
    }

}